package pers.wang.toolset.aop.log.spring.boot.autoconfigure;

import java.util.LinkedHashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pers.wang.toolset.aop.log.spring.boot.autoconfigure.annotation.ServiceLogger;

@Aspect
public class ServiceLogAspect {
	private static final Logger LOG = LoggerFactory.getLogger(ServiceLogAspect.class);

	@Pointcut("@annotation(logger)")
	public void serviceLogAspect(ServiceLogger logger) {
	};

	@Before("serviceLogAspect(logger)")
	public void doBefore(JoinPoint joinPoint, ServiceLogger logger) {
		if (logger.requestParam()) {
			String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
			Object[] paramValues = joinPoint.getArgs();
			Map<String, Object> paramMap = new LinkedHashMap<>();
			for (int i = 0; i < paramNames.length; i++) {
				paramMap.put(paramNames[i], paramValues[i]);
			}
			LOG.info("请求：{}，类：{}，方法：{}，参数：{}", logger.value(), joinPoint.getSignature().getDeclaringTypeName(),
					joinPoint.getSignature().getName(), paramMap.toString());
		}
	}

	@AfterReturning(pointcut = "serviceLogAspect(logger)", returning = "result")
	public void doAfter(JoinPoint joinPoint, Object result, ServiceLogger logger) {
		if (logger.responseData()) {
			LOG.info("响应：{}，类：{}，方法：{}，,返回：{}", logger.value(), joinPoint.getSignature().getDeclaringTypeName(),
					joinPoint.getSignature().getName(), result);
		}
	}
}
